package org.apache.ibatis.demo;

import org.apache.ibatis.demo.mapper.BlogMapper;
import org.apache.ibatis.demo.pojo.Blog;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class MyPlugin {

  /**
   * 插件原理
   * 在四大对象: Executor、ParameterHandler、ResultSetHandler、StatementHandler创建的时候
   * 1、每个创建出来的对象不是直接返回的，而是
   *      interceptorChain.pluginAll(parameterHandler);
   * 2、获取到所有的Interceptor（拦截器）（插件需要实现的接口）
   *      调用interceptor.plugin(target);返回target包装后的对象
   * 3、插件机制，我们可以使用插件为目标对象创建一个代理对象；AOP（面向切面）
   */
  @Test
  public void testPlugin() throws IOException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    Blog blog = mapper.selectBlog(1);
  }

  private SqlSessionFactory getSqlSessionFactory() throws IOException {
    String resource = "org/apache/ibatis/demo/mybatis-config.xml";
    InputStream inputStream = Resources.getResourceAsStream(resource);
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    return sqlSessionFactory;
  }

  @Test
  public void testShardTableInterceptor() throws IOException, ParseException {
    SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
    SqlSession session = sqlSessionFactory.openSession();
    BlogMapper mapper = session.getMapper(BlogMapper.class);
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    Date date = simpleDateFormat.parse("2020-07-05 12:11:11");
    List<Blog> blogs = mapper.selectBlogWithCreateTime("2020-07-05 12:11:11");
    System.out.println(blogs);
  }
}
